package net.xdclass.interceptor;

import io.jsonwebtoken.Claims;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.model.LoginUser;
import net.xdclass.util.CommonUtil;
import net.xdclass.util.JWTUtil;
import net.xdclass.util.JsonData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author guangyang
 * @since 2023-02-20
 **/
public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<LoginUser> threadLocal =new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        使用不同方法获取浏览器发送的token
        String accesssToken = request.getHeader("token");
        if (accesssToken==null){
            accesssToken=request.getParameter("token");
        }
//       token不存在或者claims对象为空则返回false
        if (StringUtils.isNotBlank(accesssToken)){
            Claims claims = JWTUtil.checkJWT(accesssToken);
            if (claims==null){
                CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
                return false;
            }
//          结果返回
            LoginUser loginUser = new LoginUser();

            loginUser.setId(Long.valueOf(claims.get("id").toString()));
            loginUser.setMail((String) claims.get("mail"));
            loginUser.setName((String) claims.get("name"));
            loginUser.setHeadImg((String)  claims.get("headImg"));

            // 使用request方法返回 ：request.setAttribute("loginUser",loginUser);最好的方法-》通过ThreadLocal传递用户信息
            threadLocal.set(loginUser);
            return true;
        }
        CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
